﻿#include"ecomsys.h"
#include <memory>
#include<algorithm>



string eComSys::centerText(const string& text) const {
		int padding = width - 2 - text.length();	
		int left = padding / 2;
		int right = padding - left;
		return string(10, ' ') + text + string(right, ' ');
	}

	// 生成边框线
string eComSys::createDivider() const {
		return string(width, divider[0]);
	}


eComSys::eComSys(int w , string div, string p )
		: width(w), divider(move(div)), prompt(move(p)){
	}

	// 添加菜单项
void eComSys:: addMainItem(const string& item) {
		mainitems.push_back(item);
	}

//=================================================================================
//商品菜单功能实现
//=================================================================================
//展示所有商品
void eComSys::displayProducts() const {
	if (products.empty()) {
		cout << "当前没有商品可展示。" << endl;
		return;
	}

	cout << "\n当前所有商品信息：" << endl;
	cout << setw(15) << left << "商户"
		<< setw(25) << left << "商品ID"
		<< setw(40) << "描述"
		<< setw(10) << "原价"
		<< setw(10) << "现价"
		<< setw(6) << "库存" << endl;
	cout << string(100, '-') << endl;

	for (const auto& item : products) {
		const string& owner = item.first.first;
		const string& id = item.first.second;
		product* prod = item.second.get();
		cout << setw(15) << left << owner
			<< setw(25) << " " + id+" "
			<< setw(40)<< prod->getDescription()
			<< fixed << setprecision(2)
			<< setw(10) << prod->getOriginalPrice()
			<< setw(10) << prod->getPrice()
			<< setw(6) << prod->getStock() << endl;
	}
}

//从所有商品里搜索
void eComSys::searchProducts() const {
	string keyword;
	double minPrice = 0, maxPrice = 0;
	cin.ignore(numeric_limits<streamsize>::max(), '\n');

	cout << "输入搜索关键词（商品名称、商户、描述；留空跳过）：";
	getline(cin, keyword);

	cout << "输入价格范围（最小-最大）：";
	while (!(cin >> minPrice >> maxPrice) || minPrice < 0 || maxPrice < minPrice) {
		cin.clear();
		cin.ignore(numeric_limits<streamsize>::max(), '\n');
		cout << "输入无效，请重新输入价格范围：";
	}

	cout << "\n搜索结果：" << endl;
	cout<< setw(15) << left << "商户"
		<< setw(25) << left << "商品ID"
		<< setw(40) << "描述"
		<< setw(10) << "现价"
		<< setw(6) << "库存" << endl;
	cout << string(95, '-') << endl;

	for (const auto& item : products) {
		const string& owner = item.first.first;
		const string& id = item.first.second;
		product* prod = item.second.get();
		bool nameMatch = keyword.empty() ||
			(prod->getProductID().find(keyword) != string::npos)||
			(prod->getDescription().find(keyword) != string::npos)||
			(prod->getOwner().find(keyword) != string::npos);
		bool priceMatch = (prod->getPrice() >= minPrice) &&
			(prod->getPrice() <= maxPrice);

		if (nameMatch && priceMatch) {
			cout << setw(15) << left << owner
				<< setw(25) << " "+id+" "
				<< setw(40) << prod->getDescription()
				<< fixed << setprecision(2)
				<< setw(10) << prod->getPrice()
				<< setw(6) << prod->getStock() << endl;
		}
	}
}

void eComSys::addProduct() {
	// 匿名函数：输入并验证浮点数
	auto inputDouble = [](const string& prompt, double minVal, double maxVal) {
		double value;
		string line;
		do {
			cout << prompt;
			getline(cin, line);
			istringstream iss(line);
			if (iss >> value) {
				char remaining;
				if (iss >> remaining) {
					cout << "输入无效，请只输入一个数字: ";
				}
				else if (value < minVal || value > maxVal) {
					cout << "输入超出范围（" << minVal << " - " << maxVal << "），请重新输入: ";
				}
				else {
					return value;
				}
			}
			else {
				cout << "输入无效，请输入数字: ";
			}
		} while (true);
		};

	// 匿名函数：输入并验证整数
	auto inputInt = [](const string& prompt, int minVal, int maxVal) {
		int value;
		string line;
		do {
			cout << prompt;
			getline(cin, line);
			istringstream iss(line);
			if (iss >> value) {
				char remaining;
				if (iss >> remaining) {
					cout << "输入无效，请只输入一个整数: ";
				}
				else if (value < minVal || value > maxVal) {
					cout << "输入超出范围（" << minVal << " - " << maxVal << "），请重新输入: ";
				}
				else {
					return value;
				}
			}
			else {
				cout << "输入无效，请输入整数: ";
			}
		} while (true);
		};

	// 商品基本信息
	if (currentUserID.empty()) {
		cout << "请先登录！" << endl;
		return;
	}
	string owner = currentUserID;//商品所有者
	string id, desc;
	cout << "\n=== 添加新商品 ===" << endl;

	// 商品ID验证
	while (true) {
		cout << "商品ID（唯一标识）: ";
		cin.ignore();
		getline(cin, id);
		ProductKey key = make_pair(owner, id);
		if (products.count(key)) {
			cout << "⚠️ 该ID已存在！" << endl;
			continue;
		}
		break;
	}

	cout << "商品描述: ";
	getline(cin, desc); // 输入商品描述信息

	double price = inputDouble("商品原价（正数）: ", 0.01, 1000000);
	int stock = inputInt("库存数量（0-9999）: ", 0, 9999);

	// 商品类型选择
	cout << "选择商品类型:\n"
		<< "1. 图书（折扣率）\n"
		<< "2. 电子产品（折扣率+税率）\n"
		<< "3. 服装（折扣率）\n"
		<< "请选择（1-3）: ";

	int type;
	string typeLine;
	while (true) {
		getline(cin, typeLine);
		istringstream iss(typeLine);
		if (iss >> type) {
			char remaining;
			if (iss >> remaining) {
				cout << "无效输入，请只输入数字（1-3）: ";
			}
			else if (type < 1 || type > 3) {
				cout << "无效选项，请重新选择（1-3）: ";
			}
			else {
				break;
			}
		}
		else {
			cout << "无效输入，请输入数字（1-3）: ";
		}
	}

	// 根据类型创建不同商品
	switch (type) {
	case 1: { // 图书
		double discount = inputDouble("折扣率（0-1）: ", 0, 1);
		products[make_pair(owner, id)] = make_unique<Book>(
			owner, id, desc, price, stock, discount);
		break;
	}
	case 2: { // 电子产品
		double discount = inputDouble("折扣率（0-1）: ", 0, 1);
		double tax = inputDouble("税率（0-1）: ", 0, 1);
		products[make_pair(owner, id)] = make_unique<Electronics>(owner,id, desc, price, stock, discount, tax);
		break;
	}
	case 3: { // 服装
		double discount = inputDouble("折扣率（0-1）: ", 0, 1);
		products[make_pair(owner, id)] = make_unique<Clothing>(owner,id, desc, price, stock, discount);
		break;
	}
	}

	cout << "✅ 商品添加成功！" << endl;
	productFileManager fd("product.json");
	fd.storeInProduct(*products[make_pair(owner, id)]);
}



// 实现商品管理功能
void eComSys::manageProducts() {
	if (currentUserID.empty()) {
		cout << "请先登录！" << endl;
		return;
	}

	// 收集当前商户的商品
	vector<ProductKey> myProducts;
	for (const auto& item : products) {
		if (item.first.first == currentUserID) {
			myProducts.push_back(item.first);
		}
	}

	if (myProducts.empty()) {
		cout << "您还没有添加任何商品。" << endl;
		return;
	}

	// 显示商品列表
	cout << "\n=== 您的商品列表 ===" << endl;
	cout << setw(3) << "序号"
		<< setw(25) << "商品ID"
		<< setw(40) << "描述"
		<< setw(10) << " 现价 "
		<< setw(6) << " 库存 " << endl;
	cout << string(85, '-') << endl;

	int index = 1;
	for (const auto& key : myProducts) {
		product* prod = products[key].get();
		cout << setw(3) << index++
			<< setw(25) << " "+key.second+" "
			<< setw(40) << prod->getDescription()
			<< fixed << setprecision(2)
			<< setw(10) << prod->getPrice()
			<< setw(6) << prod->getStock() << endl;
	}

	// 选择商品
	cout << "\n输入要修改的商品序号（0返回）: ";
	int choice;
	if (!(cin >> choice) || choice < 0 || choice > myProducts.size()) {
		cout << "输入无效！" << endl;
		return;
	}

	if (choice == 0) return;

	ProductKey selectedKey = myProducts[choice - 1];//从可变数组中挑选pair对
	product* selectedProd = products[selectedKey].get();
	modifyProduct(selectedProd);
}




// 实现商品修改功能
void eComSys::modifyProduct(product* prod) {
	auto inputDouble = [](const string& prompt, double minVal, double maxVal) {
		double value;
		string line;
		do {
			cout << prompt;
			getline(cin, line);
			istringstream iss(line);
			if (iss >> value) {
				char remaining;
				if (iss >> remaining) {
					cout << "输入无效，请只输入一个数字: ";
				}
				else if (value < minVal || value > maxVal) {
					cout << "输入超出范围（" << minVal << " - " << maxVal << "），请重新输入: ";
				}
				else {
					return value;
				}
			}
			else {
				cout << "输入无效，请输入数字: ";
			}
		} while (true);
		};

	auto inputInt = [](const string& prompt, int minVal, int maxVal) {
		int value;
		string line;
		do {
			cout << prompt;
			getline(cin, line);
			istringstream iss(line);
			if (iss >> value) {
				char remaining;
				if (iss >> remaining) {
					cout << "输入无效，请只输入一个整数: ";
				}
				else if (value < minVal || value > maxVal) {
					cout << "输入超出范围（" << minVal << " - " << maxVal << "），请重新输入: ";
				}
				else {
					return value;
				}
			}
			else {
				cout << "输入无效，请输入整数: ";
			}
		} while (true);
		};

	// 修改公共属性
	cout << "\n当前描述: " << prod->getDescription() << endl;
	string newDesc;
	cout << "输入新描述（留空保持当前）: ";
	cin.ignore();
	getline(cin, newDesc);
	if (!newDesc.empty()) {
		prod->setDescription(newDesc); // 使用 setter 方法
	}

	// 修改原价
	cout << "当前原价: " << prod->getOriginalPrice() << endl;
	double newPrice = inputDouble("输入新原价（留0保持当前）: ", 0, 1000000);
	if (newPrice > 0) {
		prod->setOriginalPrice(newPrice); // 使用 setter 方法
	}

	// 修改库存
	cout << "当前库存: " << prod->getStock() << endl;
	int newStock = inputInt("输入新库存（负数保持当前）: ", -9999, 9999);
	if (newStock >= 0) {
		prod->setStock(newStock); // 使用 setter 方法
	}

	// 修改类型特有属性
	if (auto book = dynamic_cast<Book*>(prod)) {
		cout << "当前折扣率: " << book->getDiscountRate() << endl;
		double newDiscount = inputDouble(
			"输入新折扣率（负数保持当前）",
			-1.0,   // 最小值
			1.0    // 最大值
		);
		if (newDiscount >= 0) {
			book->setDiscountRate(newDiscount);
		}
	}
	else if (auto elec = dynamic_cast<Electronics*>(prod)) {
		cout << "当前折扣率: " << elec->getDiscountRate() << endl;
		double newDiscount = inputDouble(
			"输入新折扣率（负数保持当前）",
			-1.0,   // 最小值
			1.0    // 最大值
		);
		if (newDiscount >= 0) {
			elec->setDiscountRate(newDiscount);
		}

		cout << "当前税率: " << elec->getTaxRate() << endl;
		double newTax = inputDouble("输入新税率（负数保持当前）: ", -1, 1);
		if (newTax >= 0) {
			elec->setTaxRate(std::max(0.0, newTax)); // 税率最低为0
		}
	}
	else if (auto cloth = dynamic_cast<Clothing*>(prod)) {
		cout << "当前折扣率: " << cloth->getDiscountRate() << endl;
		double newDiscount = inputDouble(
			"输入新折扣率（负数保持当前）",
			-1.0,   // 最小值
			1.0    // 最大值
		);
		if (newDiscount >= 0) {
			cloth->setDiscountRate(newDiscount);
		}
	}

	// 保存修改
	productFileManager fd("product.json");
	fd.saveAllProducts();
	cout << "✅ 商品信息已更新！" << endl;
}

//=================================================================================
// 用户菜单功能实现
//=================================================================================
//注册
void eComSys::signIn(void) {
	string usertype;
	//账号名
	string id;
	while (true) {
		cout << "请输入账号（4-12位字母数字）: ";
		cin >> id;

		if (users.count(id)) {
		cout << "该账号已存在，请重新输入\n";
		continue;
			}
		break;
		}
	//密码
	string psw, confirm;
	do {
	cout << "请输入密码（6-18位，包含字母和数字）: ";
	cin >> psw;
	cout << "请再次确认密码: ";
	cin >> confirm;
	if (psw != confirm) {
		cout << "两次输入密码不一致\n";
	}
	} while (psw != confirm);

	//用户类型
	string type;
	while (true) {
		cout << "请选择用户类型 (1. 消费者 / 2. 商家): ";
		cin >> type;

		if (type == "1") {
			usertype = "consumer";
			break;
		}
		if (type == "2") {
			usertype = "seller";
			break;
		}
		cout << "无效输入，请重新选择\n";
	}



	cout << "\n 注册成功！\n"
		<< "账号: " << id << "\n"
		<< "类型: " << usertype << "\n"
		<< "==============================\n";
	if (usertype == "seller") {
		users[id] = make_unique<seller>(id, psw, "seller");
	}
	else {
		users[id] = make_unique<consumer>(id, psw, "consumer");
	}
	userFileManager fd("user.json");
	fd.storeInuser(*users[id]);
}


//展示所有账户信息，按照用户类型进行分类
void eComSys::displayAllAc() const {
	// 辅助函数：分割字符串
	auto splitString = [](const string& s) {
		vector<string> tokens;
		istringstream iss(s);
		string token;
		while (iss >> token) {
			tokens.push_back(token);
		}
		return tokens;
		};

	// 设置表格格式
	const int colWidth[] = { 20, 15, 15, 15 };
	auto printHeader = [&]() {
		cout << left
			<< setw(colWidth[0]) << "ID"
			<< setw(colWidth[1]) << "Password"
			<< setw(colWidth[2]) << "Account"
			<< setw(colWidth[3]) << "Type"
			<< endl;
		};

	// 打印商户列表
	cout << "=== 商户列表 ===" << endl;
	printHeader();
	for (const auto& pair : users) {
		if (pair.second->getUserType() == "seller") {
			auto parts = splitString(pair.second->userInfo());
			if (parts.size() != 4) continue;

			// 格式化金额（保留两位小数）
			double account = stod(parts[3]);
			stringstream ss;
			ss << fixed << setprecision(2) << account;

			cout << left
				<< setw(colWidth[0]) << parts[0]               // ID
				<< setw(colWidth[1]) << "******"               // 隐藏密码
				<< setw(colWidth[2]) << ss.str()               // 账户金额
				<< setw(colWidth[3]) << parts[1]               // 用户类型
				<< endl;
		}
	}

	// 打印消费者列表
	cout << "\n=== 消费者列表 ===" << endl;
	printHeader();
	for (const auto& pair : users) {
		if (pair.second->getUserType() == "consumer") {
			auto parts = splitString(pair.second->userInfo());
			if (parts.size() != 4) continue;

			// 格式化金额（保留两位小数）
			double account = stod(parts[3]);
			stringstream ss;
			ss << fixed << setprecision(2) << account;

			cout << left
				<< setw(colWidth[0]) << parts[0]               // ID
				<< setw(colWidth[1]) << "******"               // 隐藏密码
				<< setw(colWidth[2]) << ss.str()               // 账户金额
				<< setw(colWidth[3]) << parts[1]               // 用户类型
				<< endl;
		}
	}
}


//登录
void eComSys::logIn() {
	string id, pwd;
	while (true) {
		cout << "请输入用户名（输入 q 返回主菜单）: ";
		cin >> id;
		if (id == "q") {
			cout << "返回主菜单。" << endl;
			return;
		}

		cout << "请输入密码: ";
		cin >> pwd;

		auto it = users.find(id);
		if (it != users.end()) {
			if (it->second->checkPassword(pwd)) {
				cout << "\n登录成功！" << endl;
				currentUserID = id; // 设置当前用户ID
				if (it->second->getUserType() == "consumer") {
					consumerMenu();
				}
				else {
					sellerMenu();
				}
				return;
			}
			else {
				cout << "❌ 密码错误，请重试！" << endl;
			}
		}
		else {
			cout << "用户不存在，是否要注册？(y/n): ";
			char choice;
			cin >> choice;
			if (tolower(choice) == 'y') {
				signIn();  // 调用注册函数
			}
			// 注册后循环继续，用户可尝试登录
		}
	}
}





//=================================================================================
// 菜单
//=================================================================================
//展现给消费者的菜单
void eComSys::consumerMenu() {
	//匿名函数，检查密码的合法性
	auto isValidPassword = [](const string& pwd) {
		if (pwd.length() < 6 || pwd.length() > 18) return false;
		bool hasAlpha = false, hasDigit = false;
		for (char c : pwd) {
			if (isalpha(c)) hasAlpha = true;
			else if (isdigit(c)) hasDigit = true;
		}
		return hasAlpha && hasDigit;
		};

	auto it = users.find(currentUserID);
	if (it == users.end()) {
		cout << "用户不存在，请重新登录！" << endl;
		return;
	}
	user* currentUser = it->second.get();//直接找到对应地址修改

	vector<string> items = {
		"修改密码", "查看余额", "充值", "查询密码",
		"浏览商品", "搜索商品", "添加商品到购物车",
		"查看/管理购物车", 
		"生成订单", "管理订单", "返回主菜单"
	};
	int choice;

	do {
		// 显示菜单
		cout << createDivider() << endl;
		cout << centerText("消费者菜单") << endl;
		for (size_t i = 0; i < items.size(); ++i) {
			cout << centerText(to_string(i + 1) + ". " + items[i]) << endl;
		}
		cout << createDivider() << endl;
		cout << "😍请选择操作序号！";

		if (!(cin >> choice)) {
			cin.clear();
			cin.ignore(numeric_limits<streamsize>::max(), '\n');
			cout << "输入无效，请输入数字！" << endl;
			continue;
		}

		switch (choice) {
		case 1: { // 修改密码
			string oldPwd, newPwd, confirmPwd;
			cout << "请输入当前密码：";
			cin >> oldPwd;
			if (!currentUser->checkPassword(oldPwd)) {
				cout << "密码错误，修改失败！" << endl;
				break;
			}

			do {
				cout << "请输入新密码（6-18位，包含字母和数字）：";
				cin >> newPwd;
			} while (!isValidPassword(newPwd) && (cout << "密码不符合要求！" << endl));

			cout << "请确认新密码：";
			cin >> confirmPwd;
			if (newPwd != confirmPwd) {
				cout << "两次输入的新密码不一致！" << endl;
				break;
			}

			currentUser->setPassword(newPwd);
			userFileManager fd("user.json");
			fd.saveAllUsers();
			cout << "密码修改成功！" << endl;
			break;
		}

		case 2: // 查看余额
			cout << "当前账户余额为：" << fixed << setprecision(2)
				<< currentUser->getAccountMoney() << "元" << endl;
			break;

		case 3: { // 余额充值
			double amount;
			cout << "请输入充值金额（正数）：";
			while (!(cin >> amount) || amount <= 0) {
				cin.clear();
				cin.ignore(numeric_limits<streamsize>::max(), '\n');
				cout << "输入无效，请输入正数：";
			}

			currentUser->recharge(amount);
			userFileManager fd("user.json");
			fd.saveAllUsers();
			cout << "充值成功！当前余额：" << fixed << setprecision(2)
				<< currentUser->getAccountMoney() << "元" << endl;
			break;
		}

		case 4: // 新增密码查询功能
			cout << "当前密码: " << currentUser->getPsw() << endl;
			break;

		case 5:
			displayProducts();
			break;
		case 6:
			searchProducts();
			break;
		case 7: { // 添加商品到购物车
			string owner, productID;
			int quantity;
			// 读取商品所有者（整行输入）
			std::cout << "请输入商品的所有者：";
			cin.ignore();
			std::getline(std::cin, owner);

			// 读取商品ID（整行输入）
			std::cout << "请输入商品的ID：";
			std::getline(std::cin, productID);

			// 读取并验证购买数量（整数输入）
			bool validInput = false;
			do {
				std::cout << "请输入购买数量：";
				if (std::cin >> quantity) {
					// 清除输入缓冲区的多余字符
					std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
					if (quantity > 0) {
						validInput = true;
					}
					else {
						std::cout << "购买数量必须为正数！" << std::endl;
					}
				}
				else {
					// 输入无效，清除错误标志并忽略错误输入
					std::cin.clear();
					std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
					std::cout << "输入无效，请输入一个整数！" << std::endl;
				}
			} while (!validInput);



			ProductKey key = { owner, productID };
			if (products.find(key) == products.end()) {
				cout << "商品不存在！" << endl;
				break;
			}

			// 获取或创建购物车，每个用户都有一个购物车，没有会直接创建，这是map容器的特性
			auto& cart = userCarts[currentUserID];
			//获取当前用户指针
			user* currentUser = users[currentUserID].get();
			cart.setConsumer(currentUser);
			//每次添加一件商品
			cart.addItem(key, quantity);
			cout << "商品已添加到购物车！" << endl;
			break;
		}
		case 8: { // 查看购物车
			auto& cart = userCarts[currentUserID];
			auto items = cart.getItems();
			if (items.empty()) {
				cout << "购物车为空！" << endl;
				break;
			}

			// 显示购物车商品时添加序号
			int index = 1;
			map<int, ProductKey> itemMap;
			double total = 0.0;
			cout << "购物车中的商品：" << endl;
			for (auto& [key, qty] : items) {
				product* p = products[key].get();
				if (p) {
					double price = p->getPrice();
					cout << index << ". 商品名称: " << key.second
						<< ", 描述: " << p->getDescription()
						<< ", 单价: " << price
						<< ", 数量: " << qty
						<< ", 小计: " << (price * qty) << endl;
					total += price * qty;
					itemMap[index++] = key;
				}
			}
			cout << "总金额: " << total << "元" << endl;

			// 新增修改选项
			cout << "\n1. 修改商品数量\n2. 删除商品\n3. 返回\n请选择操作: ";
			int action;
			cin >> action;

			if (action == 1) {
				cout << "输入要修改的商品序号: ";
				int itemNum;
				cin >> itemNum;
				if (itemMap.count(itemNum)) {
					cout << "输入新的数量: ";
					int newQty;
					cin >> newQty;
					if (newQty > 0) {
						cart.updateQuantity(itemMap[itemNum], newQty);
						cout << "数量已修改！" << endl;
					}
					else {
						cout << "数量不能为负数！" << endl;
					}
				}
			}
			else if (action == 2) {
				cout << "输入要删除的商品序号: ";
				int itemNum;
				cin >> itemNum;
				if (itemMap.count(itemNum)) {
					cart.removeItem(itemMap[itemNum]);
					cout << "商品已移除！" << endl;
				}
			}
			break;
		}
		case 9: { // 生成订单
			auto& cart = userCarts[currentUserID];
			if (cart.getItems().empty()) {
				cout << "购物车为空，无法生成订单！" << endl;
				break;
			}

			try {
				Order newOrder;
				newOrder.generateOrder(cart);
				cout << "订单生成成功！订单号：" << newOrder.getOrderId() << endl;
				cart.clear(); // 清空购物车
			}
			catch (const exception& e) {
				cout << "错误: " << e.what() << endl;
			}
			orderFileManager fd("order.json");
			fd.saveAllOrders();
			break;
		}
		case 10: { // 管理订单
			user* currentUser = users[currentUserID].get();
			vector<Order*> userOrders;
			//遍历所有该用户的历史订单
			for (const auto& [id, order] : allOrders) {
				if (order->getConsumer() == currentUser) {
					userOrders.push_back(order.get());
				}
			}

			if (userOrders.empty()) {
				cout << "暂无订单！" << endl;
				break;
			}

			// 显示订单列表
			for (size_t i = 0; i < userOrders.size(); i++) {
				Order* o = userOrders[i];
				string status;
				switch (o->getStatus()) {
				case Order::Status::UNPAID: status = "未支付"; break;
				case Order::Status::PAID: status = "已支付"; break;
				case Order::Status::CANCELLED: status = "已取消"; break;
				}
				cout << i + 1 << ". 订单号: " << o->getOrderId()
					<< " | 状态: " << status
					<< " | 金额: " << o->calculateTotal() << endl;
			}

			// 选择操作
			int choice;
			cout << "输入订单编号（0返回）: ";
			cin >> choice;
			if (choice < 1 || choice > userOrders.size()) break;

			Order* selected = userOrders[choice - 1];
			cout << "1. 支付订单\n2. 取消订单\n选择操作: ";
			cin >> choice;

			if (choice == 1) {
				if (selected->payOrder()) cout << "支付成功！" << endl;
				else cout << "支付失败（余额不足或状态无效）！" << endl;
			}
			else if (choice == 2) {
				if (selected->getStatus() == Order::Status::UNPAID)
				{
					selected->cancelOrder();
					cout << "订单已取消！" << endl;
				}
				else
					cout << "只能取消未支付订单" << endl;
			}
			orderFileManager fd("order.json");
			fd.saveAllOrders();
			break;
		}
		case 11:  // 返回主菜单选项
			return;

		default:
			cout << "无效选项，请重新输入！" << endl;
			break;
		}
	} while (true);
}




void eComSys::sellerMenu() {
	//同上
	auto isValidPassword = [](const string& pwd) {
		if (pwd.length() < 6 || pwd.length() > 18) return false;
		bool hasAlpha = false, hasDigit = false;
		for (char c : pwd) {
			if (isalpha(c)) hasAlpha = true;
			else if (isdigit(c)) hasDigit = true;
		}
		return hasAlpha && hasDigit;
		};

	auto it = users.find(currentUserID);
	if (it == users.end()) {
		cout << "用户不存在，请重新登录！" << endl;
		return;
	}
	user* currentUser = it->second.get();

	vector<string> items = {
		"查看余额", "充值", "修改密码", "查询密码",
		"管理商品", "添加商品", "浏览商品", "搜索商品", "返回主菜单"  //商户管理菜单
	};
	int choice;

	do {
		// 显示商户专属菜单
		cout << createDivider() << endl;
		cout << centerText("商户菜单") << endl;  // 修改标题为商户菜单
		for (size_t i = 0; i < items.size(); ++i) {
			cout << centerText(to_string(i + 1) + ". " + items[i]) << endl;
		}
		cout << createDivider() << endl;
		cout << "😍请选择操作序号！";

		// 输入验证
		if (!(cin >> choice)) {
			cin.clear();
			cin.ignore(numeric_limits<streamsize>::max(), '\n');
			cout << "输入无效，请输入数字！" << endl;
			continue;
		}

		switch (choice) {
		case 1: // 查看余额
			cout << "当前账户余额为：" << fixed << setprecision(2)
				<< currentUser->getAccountMoney() << "元" << endl;
			break;

		case 2: { // 余额充值
			double amount;
			cout << "请输入充值金额（正数）：";
			while (!(cin >> amount) || amount <= 0) {
				cin.clear();
				cin.ignore(numeric_limits<streamsize>::max(), '\n');
				cout << "输入无效，请输入正数：";
			}

			currentUser->recharge(amount);
			userFileManager fd("user.json");
			fd.saveAllUsers();
			cout << "充值成功！当前余额：" << fixed << setprecision(2)
				<< currentUser->getAccountMoney() << "元" << endl;
			break;
		}

		case 3: { // 修改密码
			string oldPwd, newPwd, confirmPwd;
			cout << "请输入当前密码：";
			cin >> oldPwd;
			if (!currentUser->checkPassword(oldPwd)) {
				cout << "密码错误，修改失败！" << endl;
				break;
			}

			do {
				cout << "请输入新密码（6-18位，包含字母和数字）：";
				cin >> newPwd;
			} while (!isValidPassword(newPwd) && (cout << "密码不符合要求！" << endl));

			cout << "请确认新密码：";
			cin >> confirmPwd;
			if (newPwd != confirmPwd) {
				cout << "两次输入的新密码不一致！" << endl;
				break;
			}

			currentUser->setPassword(newPwd);
			userFileManager fd("user.json");
			fd.saveAllUsers();
			cout << "密码修改成功！" << endl;
			break;
		}

		case 4: 
			cout << "当前密码: " << currentUser->getPsw()<<endl;
			break;
		case 5:
			manageProducts();
			break;
		case 6: // 新增商品添加
			addProduct();
			break;
		case 7: // 原浏览商品
			displayProducts();
			break;
		case 8: // 原搜索商品
			searchProducts();
			break;
		case 9: // 返回主菜单
			return;
		default:
			cout << "无效选项，请重新输入！" << endl;
			break;
		}
	} while (true);
}




	// 显示完整菜单
void eComSys::MainMenu() {
	auto DISPLAY = [&]() {
		cout << "\n       " << "😍请选择操作序号！";  // 带缩进的提示语
		if (!mainitems.empty()) {
			cout << "(1~" << mainitems.size() << ")";
		}
		cout << endl;

		cout << createDivider() << endl;
		cout << centerText("") << endl;  // 顶部留空

		for (size_t i = 0; i < mainitems.size(); ++i) {
			cout << centerText(to_string(i + 1) + "." + mainitems[i]) << endl;
		}

		cout << centerText("") << endl;  // 底部留空
		cout << createDivider() << endl;
		};
	//添加菜单选项
	addMainItem("退出");
	addMainItem("登录");
	addMainItem("注册");
	addMainItem("查看所有账号信息");
	addMainItem("展示商品");
	addMainItem("搜索商品");


	DISPLAY();
	int choice;

	// 输入验证循环
	while (true) {
		// 检查输入流状态
		if (!(cin >> choice)) {
			cout << "输入无效，请输入一个整数: ";
			cin.clear();  // 清除错误标志
			cin.ignore(numeric_limits<streamsize>::max(), '\n');  // 忽略缓冲区中的错误输入
			continue;
		}

		// 处理有效输入
		if (choice == SYSQUIT) {
			break;
		}

		// 检查选项范围
		bool validChoice = false;
		switch (choice) {
		case SYSLOGIN:
			cout << "login" << endl;
			try {
				logIn();
			}
			catch (const exception& e) {
				cerr << "登录异常: " << e.what() << endl;
			}
			validChoice = true;
			break;
		case SYSSIGNIN:
			cout << "signin" << endl;
			try {
				signIn();
			}
			catch (const exception& e) {
				cerr << "注册异常: " << e.what() << endl;
			}
			validChoice = true;
			break;
		case SYSCHECKALL:
			cout << "check all accounts" << endl;
			try {
				displayAllAc();
			}
			catch (const exception& e) {
				cerr << "显示账户异常: " << e.what() << endl;
			}
			validChoice = true;
			break;
		case 5://-----------------------------------<一定要隐藏每个选项具体的值
			displayProducts();
			validChoice = true;
			break;
		case 6:
			searchProducts();
			validChoice = true;
			break;
		default:
			break;
		}

		if (validChoice) {
			DISPLAY(); // 仅在有效操作后重新显示菜单
		}

		// 使用RAII确保资源正确释放
		try {
			userFileManager fd1("user.json");
			fd1.saveAllUsers(); // 保存所有用户数据
			productFileManager fd2("product.json");
			fd2.saveAllProducts();//保存所有商品数据
		}
		catch (const exception& e) {
			cerr << "保存用户数据失败: " << e.what() << endl;
		}
	}

}